source('00_util_scripts/mod_seurat.R')

mex.path <- list.files('~/append-ssd/macs3/scrna/', pattern = 'C_',
                       full.names = T)

lib.name <- mex.path |> str_extract('C_...') |>
  unique()

mex.nest <- c('barc','feat','matr') |>
  map(\(x)str_subset(mex.path, x)) |>
  set_names(c('cells','features','mtx'))

mex.nest

mtx.list <- mex.nest |>
  pmap(ReadMtx, .progress = T)

mtx.list <- mtx.list |>
  map2(lib.name, add_name_field)

mtx.mrg <- mtx.list[[1]] |>
  RowMergeSparseMatrices(mtx.list[-1])

supp.meta <- read_csv('mission/FPP/ober23/ober23.scrna.meta.csv',
                      skip = 1)

sobj <- mtx.mrg |>
  CreateSeuratObject(min.cells = 3, min.features = 200)

supp.meta <- supp.meta |>
  mutate(.cell = str_remove(...1, 'C_..._|AA\\d_'), .keep = 'unused')

sobj <- sobj |>
  left_join(supp.meta[c('.cell','Sample','NamedClust','FineClust')]) |>
  filter(!is.na(Sample))

# rds checkpoint ----------
sobj |> write_rds('mission/FPP/ober23/ober23.scrna.rds')

sobj <- read_rds('mission/FPP/ober23/ober23.scrna.rds')

sobj <- sobj |>
  NormalizeData()

sobj |>
  filter(str_detect(NamedClust, 'Kc')) |>
  DotPlot(c('TRPV3','ADRB2'), group.by = 'NamedClust', cols = 'RdYlBu')

meta.fineclus <- "
rKc1	Basal.Kc
rKc2	Spinous.Kc
rKc3	Spinous.Kc
rKc4	Spinous.Kc
rKc5	Infundibulum
rKc6	Cyc.Kc
rKc7	Inf.Segment
rKc8	Sebaceous
rKc9	Isthmus
rKc10	Eccrine
" |> read_delim(col_names = c('FineClust','FineClust.name'))

sobj <- sobj |>
  left_join(meta.fineclus)

sobj |>
  filter(str_detect(FineClust, 'rKc')) |>
  DotPlot(c('TRPV3'), group.by = 'FineClust.name', cols = 'RdYlBu') +
  labs(title = 'Scalp keratinocyte scRNA-seq', x = 'Gene', y = 'Cell type')

sobj |>
  filter(FineClust %in% c('rKc1', 'rKc3')) |>
  bill.violin('TRPV3', group.by = FineClust)

sobj |> FindMarkers(group.by = 'FineClust.name', ident.1 = 'Spinous.Kc',
                    ident.2 = 'Basal.Kc', features = 'TRPV3')

sobj |> FindMarkers(group.by = 'FineClust', ident.1 = 'rKc3',
                    ident.2 = 'rKc1', features = 'TRPV3',
                    logfc.threshold = 0)

sobj |> FindMarkers(group.by = 'NamedClust', ident.1 = c('rKc1','rKc2'),
                    ident.2 = c('rKc4','rKc5'), features = 'TRPV3')

Idents(sobj) <- 'NamedClust'

sobj |>
  filter(str_detect(NamedClust, 'Kc')) |>
  FindAllMarkers(features = 'TRPV3', only.pos = T)

sobj |>
  filter(str_detect(FineClust, 'Kc')) |>
  DotPlot('TRPV3', group.by = 'FineClust', cols = 'RdYlBu') +
  ggtitle('RNA expression in Fine CLuster')

sobj |>
  filter(str_detect(FineClust, 'Kc1$|Kc2|Kc3')) |>
  DotPlot(kegg_mva, group.by = 'FineClust', cols = 'RdYlBu') +
  ggtitle('RNA expression in Fine Cluster')

Idents(sobj) <- 'FineClust'

sobj |>
  filter(str_detect(FineClust, 'Kc')) |>
  FindAllMarkers(features = 'TRPV3', only.pos = T)

sobj |>
  filter(str_detect(FineClust, 'Kc')) |>
  FindAllMarkers(features = 'HMGCS1', only.pos = T)
